package com.aceitunaproject.server.player;

import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ClientSession;
import com.sun.sgs.app.DataManager;
import com.sun.sgs.app.NameNotBoundException;

/**
 * Player manager interface implementation
 * 
 * @author Maciej Miechowicz
 */
public class PlayerManagerImpl implements PlayerManager {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
    /**
	 * Creates a new instance of the manager
	 * 
	 * @param service backing player service
	 */
	public PlayerManagerImpl() {
		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Player getPlayer(ClientSession playerSession) {
        if(playerSession == null)
        	throw new NullPointerException("Null session");
		
		DataManager dataManager = AppContext.getDataManager();

		// TODO: add identity retrieval to obtain more detailed
		// info about the player
		String name = playerSession.getName();
		
        // try to get a player instance
        Player player = null;
        try {
            player = (Player) dataManager.getBinding(PLAYER_PREFIX + name);
        } catch (NameNotBoundException e) {
            player = new Player(name);
            dataManager.setBinding(PLAYER_PREFIX + name, player);
        }

        return player;
	}
	
}
